import React, { useState, useRef, useEffect } from 'react';
import { connect } from 'dva'

const TodoItem = ({ dispatch, item }) => {
  const [nowId, setNowId] = useState(-1)
  const editInput = useRef()
  const delTodo = (id) => {
    dispatch({ type: 'todo-dva/delTodo', payload: id })
  }
  const showEdit = (id) => {
    setNowId(id)
  }
  const hideEdit = (id) => {
    setNowId(-1)
  }
  const changeState = (id) => {
    dispatch({ type: 'todo-dva/changeState', payload: id })
  }
  const editTodo = (id, e) => {
    if(e.keyCode === 13) {
      dispatch({ type: 'todo-dva/editTodo', payload: { id, name: e.target.value } })
      setNowId(-1)
    }
  }

  useEffect(() => {
    editInput.current.focus()
  }, [nowId])
  return (
    <>
      <li className={[item.checked ? 'completed' : '', nowId === item.id ? 'editing' : ''].join(' ')} key={item.id}>
        <div className="view">
          <input className="toggle" type="checkbox" checked={item.checked} onChange={() => changeState(item.id)} />
          <label onDoubleClick={() => showEdit(item.id)}>{item.name}</label>
          <button className="destroy" onClick={() => delTodo(item.id)}></button>
        </div>
        <input className="edit" ref={editInput} defaultValue={item.name} onKeyUp={(e) => editTodo(item.id, e)} onBlur={() => hideEdit(item.id)} />
      </li>
    </>
  );
};

TodoItem.propTypes = {
};

export default connect()(TodoItem);
